import fs from 'fs-extra';
import { exec, execSync } from 'child_process';
import path from 'path';

export async function copyFiles(sourceDir: string, targetDir: string) {
    try {
        // 创建目标目录（自动递归创建）
        await fs.mkdirp(targetDir);

        // 复制并覆盖已有文件
        await fs.copy(sourceDir, targetDir, {
            overwrite: true,
            errorOnExist: false
        });

        console.log(`文件已成功复制到 ${targetDir}`);
    } catch (err: any) {
        throw new Error(`文件复制失败: ${err.message}`);
    }
}

export function runCmd(cmd: string, cwd: string) {
    try {
        return execSync(cmd, { encoding: 'utf-8', cwd });
    } catch (error) {
        const err = error as Error;
        console.error(err.message);
        throw err
    }
}

export async function readJson(filePath: string): Promise<any> {
    try {
        const data = await fs.readFile(filePath, 'utf-8');
        return JSON.parse(data)
    } catch (err) {
        console.error(`Error reading JSON file ${filePath}: ${err}`);
        throw err;
    }
}

export async function compressImages(sourceDir: string): Promise<void> {
    // TODO: Implement image compression logic
    // This would replace the Python CompressOrigen function
    console.log(`Image compression would process files in: ${sourceDir}`);
}

export async function ensureDirectory(dirPath: string): Promise<void> {
    try {
        await fs.mkdir(dirPath, { recursive: true });
    } catch (err: any) {
        if (err.code !== 'EEXIST') {
            throw err;
        }
    }
}

export async function removeDirectory(dirPath: string): Promise<void> {
    try {
        await fs.rm(dirPath, { recursive: true, force: true });
    } catch (err) {
        console.error(`Error removing directory ${dirPath}: ${err}`);
        throw err;
    }
}


export async function getFiles(dir: string, ext: string = '', isRecursive: boolean = true) {
    try {
        const files = await fs.promises.readdir(dir, { withFileTypes: true, encoding: 'utf-8' });
        let fileArray: string[] = [];

        for (const file of files) {
            const filePath = path.join(dir, file.name);
            if (file.isDirectory()) {
                if (isRecursive) {
                    // 如果是文件夹，则递归调用 getFiles 函数
                    const subFiles = await getFiles(filePath);
                    fileArray = fileArray.concat(subFiles);
                }
            } else {
                // 如果是文件，则直接添加到列表中
                if (ext && path.extname(filePath) === ext)
                    fileArray.push(filePath);
                else
                    fileArray.push(filePath);
            }
        }

        return fileArray;
    } catch (err) {
        console.error(`无法读取目录 ${dir}: ${err}`);
        return [];
    }
}

// 使用系统默认应用打开文件夹
export function openFolder(folderPath: string) {
    const absolutePath = path.resolve(folderPath);

    // 根据操作系统选择命令
    const command = process.platform === 'win32'
        ? `start "" "${absolutePath}"`
        : process.platform === 'darwin'
            ? `open "${absolutePath}"`
            : `xdg-open "${absolutePath}"`;

    exec(command);
}